<?php

namespace App\Http\Controllers\Custom;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Jobs\Basic;
use App\Models\Balance\Balance;
use App\Models\Settle\SettleCompany;
use App\Models\Manger\Manger;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Chanjet\LogFormatRecord;
use App\Services\Common\CommonExcelExport;
use Illuminate\Http\Request;
use App\Http\Validate\Custom\Custom;
use App\Models\Custom\Custom as ModelCustom;
use App\Models\Order\Outboundorder;
use App\Models\Order\Outboundordersub;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 基础信息，客户信息
 */
class CustomController extends BaseController
{

    /**
     * 添加
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'code',
            'company_code',
            'company_name',
            'category',
            'settlement_company',
            'wechat_number',
            'custom_level',
            'custom_level_2',
            'custom_level_3',
            'account_name',
            'bank_info',
            'payment_info',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email',
            'business_license',
            'account_opening_permit',
            'invoice_info',
            'preferential_price',
            'attorney'
        ]);
        $validate = new Custom('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? '';

        // 校验编码是否重复
        $resCode =$this->checkCustomCode(['cpid'=>$cpid],'code',$req_data['code'],$req_data['category']);
        if(!empty($resCode)){
            return response()->json(['code' => '001', 'msg' => '编码不允许重复']);
        }

        $resCompanyCode =$this->checkCustomCode(['cpid'=>$cpid],'company_code',$req_data['company_code'],$req_data['category']);
        if(!empty($resCompanyCode)){
            return response()->json(['code' => '001', 'msg' => '往来单位编码不能重复']);
        }

        // 新增：校验公司名称是否重复
        $resCompanyName = $this->checkCustomCode(['cpid'=>$cpid],'company_name',$req_data['company_name'],$req_data['category']);
        if(!empty($resCompanyName)){
            return response()->json(['code' => '001', 'msg' => '公司名称不能重复']);
        }

        DB::beginTransaction();
        try {
            //添加客户、供应商
            $data_custom = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'manger_name' => $manger_name,
                'code' => $req_data['code'],
                'company_code' => $req_data['company_code'],
                'company_name' => $req_data['company_name'],
                'category' => $req_data['category'],
                'settlement_company' => $req_data['settlement_company'],
                'wechat_number' => $req_data['wechat_number'],
                'custom_level' => !empty($req_data['custom_level']) ? $req_data['custom_level'] : 1,
                'custom_level_2' => !empty($req_data['custom_level_2']) ? $req_data['custom_level_2'] : 1,
                'custom_level_3' => !empty($req_data['custom_level_3']) ? $req_data['custom_level_3'] : 1,
                'preferential_price' => !empty($req_data['preferential_price']) ? $req_data['preferential_price'] : 0,
                'account_name' => $req_data['account_name'] ?? '',
                'bank_info' => $req_data['bank_info'],
                'payment_info' => $req_data['payment_info'],
                'firm_name' => $req_data['firm_name'] ?? '',
                'credit_code' => $req_data['credit_code'] ?? '',
                'firm_address' => $req_data['firm_address'] ?? '',
                'firm_phone_number' => $req_data['firm_phone_number'] ?? '',
                'firm_bank' => $req_data['firm_bank'] ?? '',
                'firm_bank_number' => $req_data['firm_bank_number'] ?? '',
                'firm_email' => $req_data['firm_email'] ?? '',
                'business_license' => $req_data['business_license'] ?? '',
                'account_opening_permit' => $req_data['account_opening_permit'] ?? '',
                'invoice_info' => $req_data['invoice_info'] ?? '',
                'attorney' => $req_data['attorney'] ?? '',
                'create_at' => time(),
            ];
            if($req_data['category'] == 3){
                //费用往来单位不需要审核，默认通过
                $data_custom['custom_status'] = 3;
                $data_custom['invoice_status'] = 3;
            }
            $custom_id = ModelCustom::create($data_custom)->id;

            //初始化账户余额
            $data_balance = [
                'cpid' => $cpid,
                'category' => $req_data['category'],
                'custom_id' => $custom_id,
                'company_name' => $req_data['company_name'],
                'company_code' => $req_data['company_code'],
                'code' => $req_data['code'],
                'manger_id' => $manger_id,
                'manger_realname' => $manger_name,
                'create_at' => time(),
            ];
            Balance::create($data_balance);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        /**
         *  同步客户/供应商档案
         *  1.首先查询往来单位分类,"结算客户/供应商" 是否存在,不存在新增
         *  2.不存在-新增，存在直接使用。  放入redis 或者放入数据表
         *  3.分类编码放入新增客户/供应商信息
         *  4.PriceGrade：{code:''}客户价格等级同步
         *
         *  非必填
         *  5.创建银行档案 Accbank:{code:''} BankAccount:''
         *  sprintf("%02d", $number);
         *
         */
        //        $chanjet_params = $this->getProviderCustomerParams($data_custom);
        //        ChanjetRequest::getInstance()->partnerCreate($chanjet_params);
        //dump($partnerClassCode);die;
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $islog = $request->islog ?? 0;
        $one = ModelCustom::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        } else {
            $outList = Outboundorder::where(['custom_id' => $id])->get()->toArray();
            $one['sale_star'] = 0;
            $one['performance_star'] = 0;

            // if (!empty($one['settlement_company'])) {
            //     $settleCompany = SettleCompany::where(['id' => $one['settlement_company']])->first();
            //     if ($settleCompany) {
            //         $one['settlement_company_name'] = $settleCompany['settle_company_name'];
            //     }
            // } else {
            //     $one['settlement_company_name'] = '';
            // }

            if (is_numeric($one['settlement_company'])) {
                $settlement_company = SettleCompany::where([['id', (int)$one['settlement_company']]])->first();
                if ($settlement_company) {
                    $settlement_company = $settlement_company->toArray();
                    $one['settlement_company_name'] = $settlement_company['settle_company_name'];
                } else {
                    $one['settlement_company_name'] = '';
                }
            } else {
                $one['settlement_company_name'] = $one['settlement_company'];
            }

            if ($outList) {
                $ids = array_column($outList, 'id');
                $weight = Outboundordersub::whereIn('p_id', $ids)->sum('weight');
                $performance = Outboundordersub::whereIn('p_id', $ids)->sum('performance');

                if ($weight >= 0 && $weight <= 1000000) {
                    $one['sale_star'] = 0;
                } elseif ($weight > 1000000 && $weight <= 3000000) {
                    $one['sale_star'] = 1;
                } elseif ($weight > 3000000 && $weight <= 5000000) {
                    $one['sale_star'] = 2;
                } elseif ($weight > 5000000 && $weight <= 10000000) {
                    $one['sale_star'] = 3;
                } elseif ($weight > 10000000 && $weight <= 20000000) {
                    $one['sale_star'] = 4;
                } else {
                    $one['sale_star'] = 5;
                }

                if ($performance >= 0 && $performance <= 300000) {
                    $one['performance_star'] = 0;
                } elseif ($performance > 300000 && $performance <= 500000) {
                    $one['performance_star'] = 1;
                } elseif ($performance > 500000 && $performance <= 1000000) {
                    $one['performance_star'] = 2;
                } elseif ($performance > 1000000 && $performance <= 2000000) {
                    $one['performance_star'] = 3;
                } elseif ($performance > 2000000 && $performance <= 3000000) {
                    $one['performance_star'] = 4;
                } else {
                    $one['performance_star'] = 5;
                }
            }

            $manger = Manger::where(['id' => $one['manger_id']])->first();
            if ($manger) {
                $manger = $manger->toArray();
                $one['manger_name_new'] = $manger['realname'];
            } else {
                $one['manger_name_new'] = '';
            }
            if($islog > 0) {
                $editLog = DB::table('custom_editlog')
                    ->where('custom_id', $id)
                    ->orderBy('id', 'desc')
                    ->first();

                if ($editLog && !empty($editLog->change_data)) {
                    // 解析change_data字段的JSON数据
                    $one['custom_editlog'] = json_decode($editLog->change_data, true);
                    // 添加操作人和操作时间信息
                    $one['custom_editlog_meta'] = [
                        'created_by' => $editLog->created_by ?? '',
                        'created_at' => isset($editLog->created_at) ? date('Y-m-d H:i:s', $editLog->created_at) : ''
                    ];
                } else {
                    $one['custom_editlog'] = '';
                    $one['custom_editlog_meta'] = '';
                }
            } else {
                $one['custom_editlog'] = '';
                $one['custom_editlog_meta'] = '';
            }
            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
        }
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id',
            'company_code',
            'company_name',
            'settlement_company',
            'wechat_number',
            'account_name',
            'bank_info',
            'payment_info',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email',
            'business_license',
            'account_opening_permit',
            'invoice_info',
            'business_license',
            'attorney'
        ]);
        $validate = new Custom('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }


        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;

        $id = $req_data['id'];
        $info = ModelCustom::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        }
        $info = $info->toArray();
        if ($info['is_freeze'] == config('constants.is_freeze.yes')) {
            return response()->json(['code' => '001', 'msg' => '被冻结无法编辑']);
        }

        if ($info['custom_status'] == 2) {
            return response()->json(['code' => '001', 'msg' => '审核中无法编辑']);
        }

        $resCompanyCode =$this->checkCustomCode(['cpid'=>$cpid,'id'=>$id],'company_code',$req_data['company_code'],$info['category']);
        if(!empty($resCompanyCode)){
            return response()->json(['code' => '001', 'msg' => '往来单位编码不能重复']);
        }
        // 记录修改前的值
        $original_data = $info;

        $data_custom = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'company_code' => $req_data['company_code'],
            'company_name' => $req_data['company_name'],
            'settlement_company' => $req_data['settlement_company'],
            'wechat_number' => $req_data['wechat_number'],
            'account_name' => $req_data['account_name'],
            'bank_info' => $req_data['bank_info'],
            'payment_info' => $req_data['payment_info'],
            'firm_name' => $req_data['firm_name'] ?? '',
            'credit_code' => $req_data['credit_code'] ?? '',
            'firm_address' => $req_data['firm_address'] ?? '',
            'firm_phone_number' => $req_data['firm_phone_number'] ?? '',
            'firm_bank' => $req_data['firm_bank'] ?? '',
            'firm_bank_number' => $req_data['firm_bank_number'] ?? '',
            'firm_email' => $req_data['firm_email'] ?? '',
            'business_license' => $req_data['business_license'] ?? '',
            'account_opening_permit' => $req_data['account_opening_permit'] ?? '',
            'invoice_info' => $req_data['invoice_info']??'',
            'attorney' => $req_data['attorney'] ?? '',
            'custom_status' => 2,           //只要修改了就是审核中
            'invoice_status' => 2,           //开票状态也重新审核
            'update_at' => time(),
        ];
        if($info['category'] == 3){
            //费用往来单位不需要审核，默认通过
            $data_custom['custom_status'] = 3;
            $data_custom['invoice_status'] = 3;
        }
        // 过滤掉不需要记录的字段
        $log_fields = [
            'company_code', 'company_name', 'settlement_company', 'wechat_number', 'account_name',
            'bank_info', 'payment_info', 'firm_name', 'credit_code', 'firm_address',
            'firm_phone_number', 'firm_bank', 'firm_bank_number', 'firm_email',
            'business_license', 'account_opening_permit', 'invoice_info', 'attorney'
        ];
//        $log_fields = [];

        // 构造修改日志数据
        $change_log = [];
        foreach ($log_fields as $field) {
            if (in_array($field, ['bank_info', 'payment_info', 'business_license', 'account_opening_permit', 'invoice_info', 'attorney'])) {
                // 处理JSON结构字段，先解析再重新编码以确保格式一致
                $original_value = isset($original_data[$field]) ? json_decode($original_data[$field], true) : null;
                $new_value = isset($data_custom[$field]) ? json_decode($data_custom[$field], true) : null;

                // 重新编码为JSON字符串进行比较，确保格式一致
                $original_json = $original_value !== null ? json_encode($original_value, JSON_UNESCAPED_UNICODE) : null;
                $new_json = $new_value !== null ? json_encode($new_value, JSON_UNESCAPED_UNICODE) : null;

                if ($original_json !== $new_json) {
                    $change_log[$field] = [
                        'before' => $original_value,
                        'after' => $new_value
                    ];
                }
            } else {
                // 处理普通字段
                if (isset($original_data[$field]) && isset($data_custom[$field])) {
                    if ($original_data[$field] != $data_custom[$field]) {
                        $change_log[$field] = [
                            'before' => $original_data[$field],
                            'after' => $data_custom[$field]
                        ];
                    }
                } elseif (isset($original_data[$field]) && !isset($data_custom[$field])) {
                    $change_log[$field] = [
                        'before' => $original_data[$field],
                        'after' => null
                    ];
                } elseif (!isset($original_data[$field]) && isset($data_custom[$field])) {
                    $change_log[$field] = [
                        'before' => null,
                        'after' => $data_custom[$field]
                    ];
                }
            }
        }
        // 如果有变更，则记录日志
        if (!empty($change_log)) {
            DB::table('custom_editlog')->insert([
                'custom_id' => $id,
                'change_data' => json_encode($change_log),
                'created_by' => $mangerinfo['realname'] ?? '',
                'created_by_id' => $manger_id,
                'created_at' => time()
            ]);
        }

        ModelCustom::where([['id', $id]])->update($data_custom);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustom::getList($request, $memberinfo, $isgetall);

        foreach ($list['list'] as $k => $v) {
            if ($request->type == 3) {
                if ($v['total_transaction_tonnage'] > 0) {
                    $list['list'][$k]['total_transaction_tonnage'] = $v['total_transaction_tonnage'] / 10000;
                }
            }
            if (is_numeric($v['settlement_company'])) {
                $settlement_company = SettleCompany::where([['id', (int)$v['settlement_company']]])->first();
                if ($settlement_company) {
                    $settlement_company = $settlement_company->toArray();
                    $list['list'][$k]['settlement_company'] = $settlement_company['settle_company_name'];
                } else {
                    $list['list'][$k]['settlement_company'] = '';
                }
            } else {
                $list['list'][$k]['settlement_company'] = $v['settlement_company'];
            }

            if (!empty($v['manger_id'])) {
                $manger = Manger::where(['id' => $v['manger_id']])->first();
                if ($manger) {
                    $manger = $manger->toArray();
                    $list['list'][$k]['manger_name_new'] = $manger['realname'];
                } else {
                    $list['list'][$k]['manger_name_new'] = '';
                }
            } else {
                $list['list'][$k]['manger_name_new'] = '';
            }

            //业务员+往来单位名称+结算公司 = T+往来单位名称
            if($list['list'][$k]['settlement_company']){
                $list['list'][$k]['tplus_company_name'] = $list['list'][$k]['manger_name_new'].'-'.$list['list'][$k]['company_name'].'*'.$list['list'][$k]['settlement_company'];
            }
            /***
             *  增加当前数据审核状态
             *   1. 客户状态，1.待审核，2审核中，3通过  4.驳回 custom_status
             *   2. 开票状态，1.待审核，2审核中，3通过  4.驳回 invoice_status
             *
            */
            if($v['custom_status'] == '1' && $v['invoice_status'] == '1'){ //初始文件导入 状态1
                $list['list'][$k]['merge_status'] = '4';//简化权限按钮判断，1，4权限一样
                $list['list'][$k]['merge_status_desc'] = '待审核';
            }
//            if($v['custom_status'] == '2' && $v['invoice_status'] == '2'){ //驳回/待审核
//                $list['list'][$k]['merge_status'] = '2';
//                $list['list'][$k]['merge_status_desc'] = '审核中';
//            }
            if(($v['custom_status'] == '2' && $v['invoice_status'] == '3') ||
                ($v['custom_status'] == '3' && $v['invoice_status'] == '2') ||
                ($v['custom_status'] == '2' && $v['invoice_status'] == '2')){ //审核中
                $list['list'][$k]['merge_status'] = '2';
                $list['list'][$k]['merge_status_desc'] = '审核中';
            }

            if($v['custom_status'] == '4' || $v['invoice_status'] == '4'){ //驳回/待审核
                $list['list'][$k]['merge_status'] = '4';
                $list['list'][$k]['merge_status_desc'] = '已驳回';
            }

            if($v['custom_status'] == '3' && $v['invoice_status'] == '3'){ //通过
                $list['list'][$k]['merge_status'] = '3';
                $list['list'][$k]['merge_status_desc'] = '通过';
            }




        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 冻结
     */
    public function dopostfreeze(Request $request)
    {
        $id = $request->id ?? 0;

        // 默认type1冻结操作，2解冻
        $type =$request->type ?? 1;
        $info = ModelCustom::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '操作失败，没有客户数据']);
        }
        $info = $info->toArray();
        if($type==1){
            if ($info['is_freeze'] == config('constants.is_freeze.yes')) {
                return response()->json(['code' => '001', 'msg' => '操作失败，已经冻结的数据不能再被冻结']);
            }

            // 余额为0，才能被冻结
            $balance = Balance::where('custom_id', $id)->first();
            if (!$balance) {
                return response()->json(['code' => '001', 'msg' => '操作失败，没有余额数据']);
            }
            $balance = $balance->toArray();
            if ($balance['balance'] > 0) {
                return response()->json(['code' => '001', 'msg' => '用户余额不为0，不能被冻结']);
            }
            $is_freeze =config('constants.is_freeze.yes');
        }else{
            $is_freeze =config('constants.is_freeze.no');
        }

        ModelCustom::where([['id', $id]])->update([
            'is_freeze' => $is_freeze,
            'update_at' => time()
        ]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 提交客户审核 财务端审核
     * status 1待审核 2审核中 3通过 4驳回
     */
    public function handlecustomreview(Request $request)
    {
        $req_data = $request->only(['id', 'custom_status']);
        $validate = new Custom('handlecustomreview');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $one = ModelCustom::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '客户信息不能为空']);
        }
        $one = $one->toArray();

        $custom_status = $req_data['custom_status'];
        if ($custom_status == 2) {
            $payment_info = json_decode($one['payment_info'], true);
            if (empty($payment_info)) {
                return response()->json(['code' => '001', 'msg' => '办款资料为空不能提审']);
            }
        }

        if ($one['is_freeze'] == config('constants.is_freeze.yes')) {
            return response()->json(['code' => '001', 'msg' => '被冻结无法提审']);
        }

        if ($custom_status == 2) {
            ModelCustom::where([['id', $id]])->update(['custom_status' => 2, 'invoice_status' => 2, 'update_at' => time()]);
        } else {
            ModelCustom::where([['id', $id]])->update(['custom_status' => $custom_status, 'update_at' => time()]);
        }
        //$start_block = microtime(true);
        $this->syncProviderCustomer($id);
        //$time_block = microtime(true)- $start_block;
        //Log::info("同步往来单位,time: ".$time_block);



        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 提交开票审核 财务端审核
     * status 1待审核、驳回 2审核中 3通过
     */
    public function handleinvoicereview(Request $request)
    {
        $req_data = $request->only(['id', 'invoice_status']);
        $validate = new Custom('handleinvoicereview');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $one = ModelCustom::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '客户信息不能为空']);
        }
        $one = $one->toArray();
        if ($one['is_freeze'] == config('constants.is_freeze.yes')) {
            return response()->json(['code' => '001', 'msg' => '被冻结无法提审']);
        }

        $invoice_status = $req_data['invoice_status'];
        if ($invoice_status == 2) {
            ModelCustom::where([['id', $id]])->update(['custom_status' => 2, 'invoice_status' => 2, 'update_at' => time()]);
        } else {
            ModelCustom::where([['id', $id]])->update(['invoice_status' => $invoice_status, 'update_at' => time()]);
        }

        $this->syncProviderCustomer($id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 模板下载
     */
    public function dodownload(Request $request)
    {
        $category = $request->category;
        if ($category == 1) {
            $filenmame = '/template/销售客户导入模板.xlsx';
        } elseif ($category == 3) {
            $filenmame = '/template/往来单位导入模板.xlsx';
        } else {
            $filenmame = '/template/供应商导入模板.xlsx';
        }

        if (file_exists(storage_path() . $filenmame) && is_file(storage_path() . $filenmame)) {
            ob_clean();
            return response()->download(storage_path() . $filenmame);
        }
        return response()->json(['code' => '001', 'msg' => '文件不存在，下载失败'], 200);
    }

    /**
     * 上传导入，先调用uploadfile，返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $custom_arr = Excel::toArray(null, $file)[0];
            if ((count($custom_arr) < 2)) {
                return response()->json(['code' => '001', 'msg' => '请填写客户信息'], 200);
            }



            $import = [];
            $category = $request->category;

            if($category == 1){
                if(count($custom_arr[0])!=21){
                    return response()->json(['code' => '001', 'msg' => '请上传正确模版'], 200);
                }
            }
            if($category == 2 || $category == 3){
                if(count($custom_arr[0])!=12){
                    return response()->json(['code' => '001', 'msg' => '请上传正确模版'], 200);
                }
            }

            unset($custom_arr[0]);


            foreach ($custom_arr as $custom) {
                if ($category == 1) {
                    $import[$custom[0]]['category'] = $category;
                    $import[$custom[0]]['code'] = $custom[0];
                    $import[$custom[0]]['company_code'] = $custom[1];
                    $import[$custom[0]]['company_name'] = $custom[2];
                    $import[$custom[0]]['settlement_company'] = $custom[3];
                    $import[$custom[0]]['wechat_number'] = $custom[4];
                    $import[$custom[0]]['account_name'] = $custom[5];
                    $import[$custom[0]]['custom_level'] = $custom[6] == '普通客户' ? 1 : 2;
                    $import[$custom[0]]['custom_level_2'] = $custom[7] == '贸易商' ? 1 : 2;

                    $import[$custom[0]]['firm_name'] = $custom[8];
                    $import[$custom[0]]['credit_code'] = $custom[9];
                    $import[$custom[0]]['firm_address'] = $custom[10];
                    $import[$custom[0]]['firm_phone_number'] = $custom[11];
                    $import[$custom[0]]['firm_bank'] = $custom[12];
                    $import[$custom[0]]['firm_bank_number'] = $custom[13];
                    $import[$custom[0]]['firm_email'] = $custom[14];

                    $import[$custom[0]]['bank_info'][] = [
                        'bank_card_no' => $custom[15],
                        'contacts' => $custom[16],
                        'phone_number' => $custom[17],
                        'bank' => $custom[18],
                        'bank_number' => $custom[19],
                        'is_default' => $custom[20] == '是'  ? 1 : 2,
                        'is_default_origin' => $custom[20]??'',
                    ];

                } else {
                    /**
                     *  $custom[6]账号 $custom[7]联系人 $custom[9]开户行
                     *  相同编码的”是否为默认银行“只能有一个“是”
                     *
                    */
                    $import[$custom[0]]['category'] = $category;
                    $import[$custom[0]]['code'] = $custom[0];
                    $import[$custom[0]]['company_code'] = $custom[1];
                    $import[$custom[0]]['company_name'] = $custom[2];
                    $import[$custom[0]]['settlement_company'] = $custom[3];
                    $import[$custom[0]]['wechat_number'] = $custom[4];
                    $import[$custom[0]]['account_name'] = $custom[5];

                    $import[$custom[0]]['bank_info'][] = [
                        'bank_card_no' => $custom[6],
                        'contacts' => $custom[7],
                        'phone_number' => $custom[8],
                        'bank' => $custom[9],
                        'bank_number' => $custom[10],
                        'is_default' => $custom[11] == '是'  ? 1 : 2,
                        'is_default_origin' => $custom[11]??'',
                    ];
                    if($category == 3){
                        //费用往来单位不需要审核，默认通过
                        $import[$custom[0]]['custom_status'] = 3;
                        $import[$custom[0]]['invoice_status'] = 3;
                    }
                }
            }

            if ($import) {
                foreach ($import as $key => $value) {
                    if (empty($value['code'])) {
                        continue;
                    }
                    $is_default_arr = array_column($import[$key]['bank_info'],'is_default_origin');
                    $count_is_default = array_count_values($is_default_arr);
                    if(!isset($count_is_default['是']) || $count_is_default['是'] === 0){
                        return response()->json(['code' => '001', 'msg' => "编码：".$value['code'].',未设置默认银行']);
                    }
                    if($count_is_default['是'] > 1){
                        if($import[$key]['category'] == '1'){
                            return response()->json(['code' => '001', 'msg' => "同一客户的默认银行信息不能为多个"]);
                        }
                        if($import[$key]['category'] == '2'){
                            return response()->json(['code' => '001', 'msg' => "同一供应商的默认银行信息不能为多个"]);
                        }

                    }
                    $import[$key]['bank_info'] = json_encode($value['bank_info']);
                }
            }

            $mangerinfo = $this->mangerinfo;
            $cpid = $mangerinfo['cpid'] ?? 0;
            $manger_id = $mangerinfo['id'] ?? 0;
            $manger_name = $mangerinfo['realname'] ?? '';

            foreach ($import as $item) {
                if (empty($item['code'])) {
                    continue;
                }

                $codeRes =$this->checkCustomCode(['cpid'=>$cpid],'code',$item['code'],$item['category']);
                if(!empty($codeRes)){
                    return response()->json(['code' => '001', 'msg' => '编码不允许重复']);
                }

                $comCodeRes =$this->checkCustomCode(['cpid'=>$cpid],'company_code',$item['company_code'],$item['category']);
                if(!empty($comCodeRes)){
                    return response()->json(['code' => '001', 'msg' => '往来单位编码不允许重复']);
                }

                if ($item['bank_info']) {
                    $bank_info = json_decode($item['bank_info'], true);
                }
                foreach ($bank_info as $bank) {

                    if (empty($bank['bank_card_no'])) {
                        return response()->json(['code' => '001', 'msg' => '账号不能为空']);
                    }
                    if (empty($bank['contacts'])) {
                        return response()->json(['code' => '001', 'msg' => '联系人不能为空']);
                    }
                    if (empty($bank['bank'])) {
                        return response()->json(['code' => '001', 'msg' => '开户行信息不能为空']);
                    }

                    // 账号33位
                    if (strlen($bank['bank_card_no']) > 33) {
                        return response()->json(['code' => '001', 'msg' => '账号不能超过33位']);
                    }
                    if (!is_numeric($bank['phone_number'])) {
                        return response()->json(['code' => '001', 'msg' => '联系人电话格式不正确']);
                    }
                    if (!is_numeric($bank['bank_number'])) {
                        return response()->json(['code' => '001', 'msg' => '开户行账号格式不正确']);
                    }

                }
            }
            DB::beginTransaction();
            try {
                foreach ($import as $item) {
                    if (empty($item['code'])) {
                        continue;
                    }

                    $settlement_company = SettleCompany::where([
                        ['cpid', $cpid],
                        ['settle_company_name', $item['settlement_company']],
                        ['status', 1]
                    ])->first();
                    if (!$settlement_company) {
                        return response()->json(['code' => '001', 'msg' => '编码【' . $item['code'] . '】结算公司错误']);
                    } else {
                        $settlement_company = $settlement_company->toArray();
                    }

                    $data = [
                        'cpid' => $cpid,
                        'manger_id' => $manger_id,
                        'manger_name' => $manger_name,
                        'code' => $item['code'],
                        'company_code' => $item['company_code'],
                        'company_name' => $item['company_name'],
                        'category' => $item['category'],
                        'settlement_company' => $settlement_company['id'] ?? 0,
                        'wechat_number' => $item['wechat_number'],
                        'custom_level' => !empty($item['custom_level']) ? $item['custom_level'] : 1,
                        'account_name' => $item['account_name'],
                        'bank_info' => $item['bank_info'],
                        'payment_info' => '[]',
                        'firm_name' => $item['firm_name'] ?? '',
                        'credit_code' => $item['credit_code'] ?? '',
                        'firm_address' => $item['firm_address'] ?? '',
                        'firm_phone_number' => $item['firm_phone_number'] ?? '',
                        'firm_bank' => $item['firm_bank'] ?? '',
                        'firm_bank_number' => $item['firm_bank_number'] ?? '',
                        'firm_email' => $item['firm_email'] ?? '',
                        'business_license' => '[]',
                        'account_opening_permit' => '[]',
                        'attorney' => '[]',
                        'invoice_info' => '[]',
                        'custom_status' => 1,
                        'invoice_status' => 1,
                        'create_at' => time(),
                    ];
                    $custom_id = ModelCustom::create($data)->id;

                    $data = [
                        'cpid' => $cpid,
                        'category' => $item['category'],
                        'custom_id' => $custom_id,
                        'company_name' => $item['company_name'],
                        'company_code' => $item['company_code'],
                        'code' => $item['code'],
                        'manger_id' => $manger_id,
                        'manger_realname' => $manger_name,
                        'create_at' => time(),
                    ];
                    Balance::create($data);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '操作成功'], 200);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $category = $request->category ?? 1;
        $memberinfo = $this->mangerinfo;
        $cpid = $memberinfo['cpid'] ?? 0;
        $isgetall = $request->isgetall ?? 1;
        $list = ModelCustom::getList($request, $memberinfo, $isgetall);

        $exceldata = [];

        if ($category == 1) {
            $row = [
                [
                    'code' => '编码',
                    'company_code' => '往来单位编码',
                    'company_name' => '往来单位名称',
                    'category' => '性质',
                    'manger_name' => '分管人员',
                    'settlement_company' => '结算公司',
                    'wechat_number' => '微信号',
                    'custom_level' => '客户价等级',
                    'account_name' => '户名',

                    'firm_name' => '公司名称',
                    'credit_code' => '统一信用代码',
                    'firm_address' => '公司地址',
                    'firm_phone_number' => '公司电话',
                    'firm_bank' => '公司开户行',
                    'firm_bank_number' => '公司账户',
                    'firm_email' => '公司邮箱',

                    'business_license' => '上传营业执照',
                    'account_opening_permit' => '上传开户许可证',
                    'attorney' => '上传委托书',
                    'invoice_info'=> '开票信息',

                    'bank' => '开户行',
                    'bank_number' => '开户行行号',
                    'bank_card_no' => '账号',
                    'contacts' => '联系人',
                    'phone_number' => '联系人电话',
                    'is_default' => '是否为默认银行',

                    'custom_status' => '客户状态',
                    'invoice_status' => '开票状态',
                    'is_freeze' => '是否冻结',
                ]
            ];

            $datawith = [
                'A' => '50', 'B' => '50', 'C' => '25', 'D' => '25', 'E' => '25', 'F' => '50', 'G' => '25', 'H' => '25', 'I' => '25', 'J' => '50', 'K' => '50', 'L' => '25', 'M' => '50', 'N' => '25', 'O' => '25', 'P' => '25', 'Q' => '25', 'R' => '25', 'S' => '50', 'T' => '25', 'U' => '50', 'V' => '25', 'W' => '25', 'X' => '25', 'Y' => '25', 'Z' => '25', 'AA' => '25', 'AB' => '25', 'AC' => '25'
            ];
        } else {
            $row = [
                [
                    'code' => '编码',
                    'company_code' => '往来单位编码',
                    'company_name' => '往来单位名称',
                    'category' => '性质',
                    'manger_name' => '分管人员',
                    'settlement_company' => '结算公司',
                    'wechat_number' => '微信号',
                    'account_name' => '户名',
                    'bank' => '开户行',
                    'bank_number' => '开户行行号',
                    'bank_card_no' => '账号',
                    'contacts' => '联系人',
                    'phone_number' => '联系人电话',
                    'is_default' => '是否为默认银行',

                    'payment_info' => '办款资料',

                    'custom_status' => '客户状态',
                    'invoice_status' => '开票状态',
                    'is_freeze' => '是否冻结',
                ]
            ];
            $datawith = [
                'A' => '50', 'B' => '50', 'C' => '25', 'D' => '25', 'E' => '25', 'F' => '50', 'G' => '25', 'H' => '25', 'I' => '25', 'J' => '50', 'K' => '50', 'L' => '25', 'M' => '50', 'N' => '25', 'O' => '25', 'P' => '25', 'Q' => '25', 'R' => '25', 'S' => '25'
            ];
        }


        foreach ($list['list'] as $val) {
            switch ($val['category']) {
                case 1:
                    $category = '结算客户';
                    break;
                case 2:
                    $category = '供应商';
                    break;
            }

            switch ($val['custom_level']) {
                case 1:
                    $custom_level = '普通客户';
                    break;
                case 2:
                    $custom_level = '优惠客户';
                    break;
            }

            switch ($val['custom_status']) {
                case 1:
                    $custom_status = '待审核';
                    break;
                case 2:
                    $custom_status = '审核中';
                    break;
                case 3:
                    $custom_status = '通过';
                    break;
                case 4:
                    $custom_status = '已驳回';
                    break;
            }

            switch ($val['invoice_status']) {
                case 1:
                    $invoice_status = '待审核';
                    break;
                case 2:
                    $invoice_status = '审核中';
                    break;
                case 3:
                    $invoice_status = '通过';
                    break;
                case 4:
                    $invoice_status = '已驳回';
                    break;
            }

            switch ($val['is_freeze']) {
                case 1:
                    $is_freeze = '正常';
                    break;
                case 2:
                    $is_freeze = '冻结';
                    break;
            }

            $manger = Manger::where(['id' => $val['manger_id']])->first();
            if ($manger) {
                $manger_name = $manger->realname;
            } else {
                $manger_name = '';
            }


            if (is_numeric($val['settlement_company'])) {
                $settlement_company = SettleCompany::where([
                    ['cpid', $cpid],
                    ['id', $val['settlement_company']],
                    ['status', 1]
                ])->first();
                if ($settlement_company) {
                    $settlement_company = $settlement_company->toArray();
                    $settlement_company = $settlement_company['settle_company_name'];
                } else {
                    $settlement_company = '';
                }
            } else {
                $settlement_company = $val['settlement_company'];
            }


            $bank_info = json_decode($val['bank_info'], true);
            if ($bank_info) foreach ($bank_info as $value) {
                switch ($value['is_default']) {
                    case 1:
                        $is_default = '是';
                        break;
                    case 2:
                        $is_default = '否';
                        break;
                }

                if ($val['category'] == 1) {
                    $row[] = [
                        'code' => $val['code'],
                        'company_code' => $val['company_code'],
                        'company_name' => $val['company_name'],
                        'category' => $category,
                        'manger_name' => $manger_name,
                        'settlement_company' => $settlement_company,
                        'wechat_number' => $val['wechat_number'],
                        'custom_level' => $custom_level,
                        'account_name' => $val['account_name'],

                        'firm_name' => $val['firm_name'],
                        'credit_code' => $val['credit_code'],
                        'firm_address' => $val['firm_address'],
                        'firm_phone_number' => $val['firm_phone_number'],
                        'firm_bank' => $val['firm_bank'],
                        'firm_bank_number' => $val['firm_bank_number'],
                        'firm_email' => $val['firm_email'],

                        'business_license' => $val['business_license'],
                        'account_opening_permit' => $val['account_opening_permit'],
                        'attorney' => $val['attorney'],
                        'invoice_info'=> $val['invoice_info'],

                        'bank' => $value['bank'],
                        'bank_number' => $value['bank_number'],
                        'bank_card_no' => $value['bank_card_no'],
                        'contacts' => $value['contacts'],
                        'phone_number' => $value['phone_number'],
                        'is_default' => $is_default,

                        'custom_status' => $custom_status,
                        'invoice_status' => $invoice_status,
                        'is_freeze' => $is_freeze,
                    ];
                } else {
                    // $payment_info = json_decode($val['payment_info'], true);
                    // if ($payment_info) foreach ($payment_info as $v) {
                    //     $payment[] = $v['url'];

                    // }
                    // if ($payment && is_array($payment)) {
                    //     $payment = implode(',', $payment);
                    // } else {
                    //     $payment = '';
                    // }

                    $row[] = [
                        'code' => $val['code'],
                        'company_code' => $val['company_code'],
                        'company_name' => $val['company_name'],
                        'category' => $category,
                        'manger_name' => $manger_name,
                        'settlement_company' => $settlement_company,
                        'wechat_number' => $val['wechat_number'],
                        'account_name' => $val['account_name'],

                        'bank' => $value['bank'],
                        'bank_number' => $value['bank_number'],
                        'bank_card_no' => $value['bank_card_no'],
                        'contacts' => $value['contacts'],
                        'phone_number' => $value['phone_number'],
                        'is_default' => $is_default,

                        // 'payment_info' => $payment,
                        'payment_info' => $val['payment_info'],

                        'custom_status' => $custom_status,
                        'invoice_status' => $invoice_status,
                        'is_freeze' => $is_freeze,
                    ];
                }
            }
        }

        if ($category == 1) {
            $name = '客户';
        } else {
            $name = '供应商';
        }
        $filename = $name . '信息导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }


    /**
     *  同步供应商、客户信息
     *
     *
     */

    public function syncProviderCustomer($id)
    {
        $custom = ModelCustom::where(["is_freeze" => 1, 'id' => $id])->first();
        if ($custom["custom_status"] == 3 && $custom["invoice_status"] == 3) {
            $requestData = [
                "api" => "partnerCreate",
                "param" => $custom,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Custom::dispatch($requestData);

//            if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//                $chanjet_params = $this->getProviderCustomerParams($custom);
//                ChanjetRequest::getInstance()->partnerCreate($chanjet_params, $this->mangerinfo['org_id']);
//            }


        }
        return true;
    }
    /**
     *  获取往来单位参数
     *  2025.01.03  往来单位编码必须唯一，测试只能使用一个账套。可能会报错 往来单位编码重复
     *
     *
     * */
    public function getProviderCustomerParams($data){
        $Partner = $this->getProviderCustomerPartner($data['category']);
        $PartnerBankInfoDTOs = $this->getPartnerBankinfoDtos($data);
        $PartnerAddresDTOs = $this->getPartnerAddresDTOs($data);
        $settleCompanyName = SettleCompany::where('id',$data["settlement_company"])->value("settle_company_name");

        $Manger = Manger::where('id',$data["manger_id"])->first();

        if(empty($Manger["code_no"])){ //分管人员必须存在
            LogFormatRecord::error($this->mangerinfo,["api_name"=>"partnerClassCreate/partnerClassQuery","err"=>'分管人员必须存在',"business_type"=>"客户/供应商"]);
            return false;
        }

        $dto = [
            "dto"=>[
                "Code"=>$data["company_code"],
                "Name"=>$data["manger_name"].'_'.$data["company_name"].'_'.$settleCompanyName,//业务员（登录人员）-客户名称-结算公司
                "PartnerType"=>["Code"=>$Partner['partnerTypeCode']],
                "PartnerClass"=>["Code"=>$Partner['PartnerClassCode']],
                "TaxRate" => ["Name" => "0"],
                "SaleMan" => ["Code" => $Manger["code_no"]],//分管人员编码
            ]
        ];
        if(!empty($Manger["sys_dpm_id"])){
            $dto["dto"]["SaleDepartment"]["code"] = $Manger["sys_dpm_id"];
        }
        //$payment_info = json_decode($data["payment_info"],true);
        if($data['category'] == '1'){
            $dto["dto"]["PartnerBankInfoDTOs"]["DynamicPropertyKeys"] = ["priuserdefnvc1","priuserdefnvc2"];
            $dto["dto"]["PartnerBankInfoDTOs"]["DynamicPropertyValues"] = [$data["wechat_number"],$data["account_name"]];
        }
        if($data['category'] == '2'){
            $dto["dto"]["PartnerBankInfoDTOs"]["DynamicPropertyKeys"] = ["priuserdefnvc1","priuserdefnvc2"];
            $dto["dto"]["PartnerBankInfoDTOs"]["DynamicPropertyValues"] = [$data["wechat_number"],$data["account_name"]];
        }
        if(!empty($PartnerBankInfoDTOs)){
            $dto["dto"]["PartnerBankInfoDTOs"] = $PartnerBankInfoDTOs;
        }
        if(!empty($PartnerAddresDTOs)){
            $dto["dto"]["PartnerAddresDTOs"] = $PartnerAddresDTOs;
        }
        return $dto;
    }
    //往来单位分类编码
    public function getProviderCustomerPartner($category)
    {
        if ($category == 1) { //客户
            $partnerClassCode = ChanjetRequest::getInstance()->partnerClassQuery(["param" => ["Name" => "结算客户"]], $this->mangerinfo['org_id']);
            $partnerType = "01";
            if (empty($partnerClassCode)) {
                //创建分类后，返回null
                ChanjetRequest::getInstance()->partnerClassCreate(["dto" => ["code" => "settle_customer", "name" => "结算客户"]], $this->mangerinfo['org_id']);
                $partnerClassCode = ChanjetRequest::getInstance()->partnerClassQuery(["param" => ["Name" => "结算客户"]], $this->mangerinfo['org_id']);
            }
        }
        if ($category == 2) { //供应商
            $partnerClassCode = ChanjetRequest::getInstance()->partnerClassQuery(["param" => ["Name" => "供应商"]], $this->mangerinfo['org_id']);
            $partnerType = "00";
            if (empty($partnerClassCode)) {
                //创建分类后，返回null
                ChanjetRequest::getInstance()->partnerClassCreate(["dto" => ["code" => "provider", "name" => "供应商"]], $this->mangerinfo['org_id']);
                $partnerClassCode = ChanjetRequest::getInstance()->partnerClassQuery(["param" => ["Name" => "供应商"]], $this->mangerinfo['org_id']);
            }
        }
        //查询客户/供应商 分类编码失败
        if(!isset($partnerClassCode) || !isset($partnerClassCode[0]) || !isset($partnerClassCode[0]['Code'])){
            LogFormatRecord::error($this->mangerinfo,["api_name"=>"partnerClassCreate/partnerClassQuery","err"=>'T+查询/创建客户/供应商分类编码失败',"business_type"=>"客户/供应商"]);
        }
        return ["partnerTypeCode" => $partnerType, "PartnerClassCode" => $partnerClassCode[0]["Code"]];
    }
    //获取供应商银行信息
    public function getPartnerBankinfoDtos($data){
        $res = [];
        if(isset($data['bank_info'])){
            $bankInfo = json_decode($data['bank_info'], true);
            foreach ($bankInfo as $item) {
                //$this->createBankAccount($item);//忽略错误 直接创建
                $res[] = [
                    "PartnerAccbank" => ["Name"=>$item["bank"]],//开户银行名称
                    "PartnerBankAccount" => $item["bank_card_no"],//账号
                    "IsDefaultBank" => $item["is_default"]=='1'? true : false,//是否默认银行账号
                    "Status" => "1",//1：新增 2：修改 3：删除
                ];
            }
        }
        return $res;
    }
    //获取供应商联系方式
    public function getPartnerAddresDTOs($data){
        $res = [];
        if(isset($data['bank_info'])){
            $bankInfo = json_decode($data['bank_info'], true);
            foreach ($bankInfo as $item) {
                $res[] = [
                    "Contact" => $item["contacts"],//开户银行名称
                    "TelephoneNo" => $item["phone_number"],//地址简称
                    "IsDefaultBank" => $item["is_default"]=='1'? true : false,//是否默认地址
                    "Status" => "1",//1：新增 2：修改 3：删除
                ];
            }
        }
        return $res;
    }
    /**
     *  获取往来单位
     *
     */
    public function getCustomerLevel($data)
    {
        $PriceGradeCode = '05';
        if (isset($data['custom_level']) && $data["custom_level"] > 1) {
            if (!empty($data["custom_level3"])) {
                if ($data["custom_level3"] <= 5) {
                    $PriceGradeCode = $data["custom_level3"] - 1;
                }
                $PriceGradeCode = sprintf("%02d", $PriceGradeCode);
            }
        }
        return $PriceGradeCode;
    }

    /***
     *  获取拼接客户名称
     *  业务员名称-客户名称-结算公司
     *
    */
    public static function getFullnameInCustom($data =[]){
        $custom_full_name = [];
        $settlement_company_name = '';

        //获取 业务员名称
        if (!empty($data['manger_id'])) {
            $manger = Manger::where(['id' => $data['manger_id']])->first();
            $custom_full_name[] = $manger['realname'];
        }else{
            $custom_full_name[] = '';
        }

        $custom_full_name[] = $data['company_name'];

        if(!is_numeric($data['settlement_company'])){
            $settlement_company_name = $data['settlement_company'];
        }else{
            $settlement_company = SettleCompany::where([['id', (int)$data['settlement_company']]])->first();
            if ($settlement_company) {
                $settlement_company = $settlement_company->toArray();
                $settlement_company_name = $settlement_company['settle_company_name'];
            }
        }
        $custom_full_name[] = $settlement_company_name;
        $custom_full_name_filter = array_filter($custom_full_name,function($item){
            return !empty($item);
        });
        // 转换为索引数组
        $custom_full_name_indexed = array_values($custom_full_name_filter);

        // 按照新规则拼接：第一个和第二个用_连接，第二个和第三个用*连接
        if (count($custom_full_name_indexed) == 1) {
            $custom_full_name_str = $custom_full_name_indexed[0];
        } else if (count($custom_full_name_indexed) == 2) {
            $custom_full_name_str = $custom_full_name_indexed[0] . '-' . $custom_full_name_indexed[1];
        } else if (count($custom_full_name_indexed) >= 3) {
            $custom_full_name_str = $custom_full_name_indexed[0] . '-' . $custom_full_name_indexed[1] . '*' . $custom_full_name_indexed[2];
        } else {
            $custom_full_name_str = '';
        }

        return $custom_full_name_str;
    }


    public  function checkCustomCode($param,$key='code',$code,$category)
    {
        // 校验编码是否重复
        $id =$param['id']??0;
        $where['cpid']=$param['cpid'];
        $where[$key]=$code;
        $where['category']=$category;
        $where['is_freeze']=1;
        $isexist = ModelCustom::query()
            ->where($where)
            ->when($id>0,function ($query)use ($id){
                $query->where('id','<>',$id);
            })
            ->first();
        $isexist =empty($isexist)? [] :$isexist->toArray();
        return $isexist;

    }
}
